package com.xinzhi.savingpot.userinfo.service.impl;


import com.xinzhi.savingpot.userinfo.entity.UserInfo;
import com.xinzhi.savingpot.userinfo.mapper.IloginMapper;
import com.xinzhi.savingpot.userinfo.service.ILoginService;
import com.xinzhi.savingpot.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IloginMapper rid;
    @Autowired
    private RedisUtil redisUtil;





    /**
     * 手机号密码效验
     * @param phone
     * @param password
     * @return
     */

    @Override
    public BaseResponse Login(String phone, String password) {

        if (phone==null&&password==null){

            return new BaseResponse(0,"手机号密码不能为空");
        }
            UserInfo userInfo = rid.selectToken(phone,MD5Util.stringMD5(password));
            if (userInfo==null){
                return new BaseResponse(-1,"账号密码错误");
            }
        /**
         * 生成token
         */
        String token = LoginServiceImpl.this.createToken(phone);
        return new BaseResponse(1,"登陆成功",token);
    }



    /**
     * 根据id查询信息
     * @param userid
     * @return
     */
    @Override
    public UserInfo findUserById(int userid) {
        UserInfo dbuser = rid.findByid(userid);
        return dbuser;
    }

    @Override
    public BaseResponse sendCode(String phone) {
        if (phone != null) {
            if (rid.selectphone(phone) >0) {
                String code1 = NoteUtil.VCode();
                NoteUtil.send(phone, code1);
                redisUtil.set(phone, code1, 300);
                return new BaseResponse(100, "发送成功");
            }
            return new BaseResponse(100, "发送失败");

        }
        return new BaseResponse(100,"请输入手机号获取");
    }


    @Override
    public BaseResponse checkCode(String phone, String code) {

        if (code.equals(redisUtil.get(phone))){
            /**
             * 生成token
             */
            String token = LoginServiceImpl.this.createToken(phone);
            return new BaseResponse(200,"登陆成功");
        }else
        return new BaseResponse(200,"登陆失败");
    }

    /**
     *生成token
     * @param phone
     * @return
     */
    @Override
    public String createToken(String phone) {
        UserInfo userInfo = rid.selecUserInfo(phone);
        //生成token
        String token = JwtUtils.createJsonWebToken(userInfo);
        redisUtil.set("Token:" + userInfo.getUserId(), token,60*60*1000);
        redisUtil.set("User"+userInfo.getUserId(),userInfo,60*60*24*7);
        return null;
    }


}
